package com.caesar.gxmz;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.widget.Toast;

import com.blankj.utilcode.util.ToastUtils;
import com.caesar.gxmz.data.AppAdvertVideoBean;
import com.caesar.gxmz.network.AppNetworkUtils;
import com.caesar.gxmz.network.NetworkCallback;
import com.caesar.gxmz.network.NetworkUtils;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.io.File;
import java.util.List;

import static com.caesar.gxmz.network.ApiConfig.CODE_SUCC;
import static com.caesar.gxmz.network.ApiConfig.THINKCMF_PATH;

public class WelcomeActivity extends Activity{
	private Context context;
	public static boolean isForeground = false;
	public static int REQUESTCODE = 1;
    private static final String LOG_TAG = "ImageDownloader";

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 0:
					Intent intent = new Intent();
					intent.setClass(WelcomeActivity.this, MainActivity.class);
					startActivity(intent);
					finish();
					break;
				case 1:
					NetworkUtils.fetchInfo(AppNetworkUtils.initRetrofitApi().getAppSlideList(),
							new NetworkCallback<AppAdvertVideoBean>() {
								@Override
								public void onSuccess(AppAdvertVideoBean baseBean) {
									if (baseBean.getCode() == CODE_SUCC) {
										AppAdvertVideoBean.AdvertVideoBean videoBean = baseBean.getReferer();
										String picString=videoBean.getSlide_pic();
										String urlString=videoBean.getSlide_url();
										if (!picString.startsWith("http://")) {
											picString = THINKCMF_PATH + picString;
										}
										if (!urlString.startsWith("http://")) {
											urlString ="http://"+urlString;
										}
										UserInfoUtils.setAppImage(picString, WelcomeActivity.this);
										UserInfoUtils.setAppURL(urlString, WelcomeActivity.this);
									}else {
										UserInfoUtils.setAppImage("", WelcomeActivity.this);
										UserInfoUtils.setAppURL("", WelcomeActivity.this);
									}
								}

								@Override
								public void onFailure(Throwable t) {
									ToastUtils.showShort("网络有延迟");
								}
							});

					break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.welcome_activity);
//		JPushInterface.setDebugMode(false);
//		JPushInterface.init(this);
		System.out.println("welcome");
//	Intent shortcutintent = new Intent(
//			"com.android.launcher.action.INSTALL_SHORTCUT");
//	shortcutintent.putExtra("duplicate", false);
//	shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
//	Parcelable icon = Intent.ShortcutIconResource.fromContext(
//			getApplicationContext(), R.drawable.ic_launcher);
//	shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
//	shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(
//			getApplicationContext(), WelcomeActivity.class));
//	sendBroadcast(shortcutintent);
        if (hasSdcard()) {
            String pathName = Environment.getExternalStorageDirectory()
                    + File.separator + LOG_TAG;
            File file = new File( pathName );
            if (!file.isDirectory()) {
                file.mkdir();
            }
        } else {
            Toast.makeText( this, "您的手机可能缺少储存卡", Toast.LENGTH_SHORT )
                    .show();
        }
//		handler.sendEmptyMessage(1);
		requestPerssion();
//		if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED){
////			download();
//		}else {
//			//申请权限
//			ActivityCompat.requestPermissions(WelcomeActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUESTCODE);
//		}
	}
	/**
	 * make true current connect service is wifi
	 * @return
	 */

    public boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals( Environment.MEDIA_MOUNTED )) {
            return true;
        } else {
            return true;
        }
    }

	private static boolean isWifi(Context mContext) {
		ConnectivityManager connectivityManager = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null
				&& activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
			return true;
		}
		return false;
	}

	//public boolean note_Intent(Context context) {
	//	ConnectivityManager con = (ConnectivityManager) context
	//		.getSystemService(Context.CONNECTIVITY_SERVICE);
	//	NetworkInfo networkinfo = con.getActiveNetworkInfo();
	//	if (networkinfo == null || !networkinfo.isAvailable()) {
	//	// 当前网络不可用
	//		Toast.makeText(context.getApplicationContext(), "请检查网络设置",
	//		Toast.LENGTH_SHORT).show();
	//		return false;
	//	}
	//	boolean wifi = con.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
	//		.isConnectedOrConnecting();
	//	if (!wifi) { // 提示使用wifi
	//		Toast.makeText(context.getApplicationContext(), "建议您使用WIFI以减少流量！",
	//		Toast.LENGTH_SHORT).show();
	//	}
	//	return true;
	//
	//}
	//private MessageReceiver mMessageReceiver;
	//public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
	//public static final String KEY_TITLE = "title";
	//public static final String KEY_MESSAGE = "message";
	//public static final String KEY_EXTRAS = "extras";
	//
	//public void registerMessageReceiver() {
	//	mMessageReceiver = new MessageReceiver();
	//	IntentFilter filter = new IntentFilter();
	//	filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
	//	filter.addAction(MESSAGE_RECEIVED_ACTION);
	//	registerReceiver(mMessageReceiver, filter);
	//}
	//
	//public class MessageReceiver extends BroadcastReceiver {
	//
	//	@Override
	//	public void onReceive(Context context, Intent intent) {
	//		if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
	//          String messge = intent.getStringExtra(KEY_MESSAGE);
	//          String extras = intent.getStringExtra(KEY_EXTRAS);
	//          StringBuilder showMsg = new StringBuilder();
	//          showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
	//          if (!JPushExampleUtil.isEmpty(extras)) {
	//        	  showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
	//          }
	//         // setCostomMsg(showMsg.toString());
	//		}
	//	}
	//}
	@Override
	protected void onResume() {
		isForeground = true;
//		JPushInterface.onResume(this);
		super.onResume();
	}


	@Override
	protected void onPause() {
		isForeground = false;
//		JPushInterface.onPause(this);
		super.onPause();
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private void requestPerssion() {

		AndPermission.with( this )
				.permission( Permission.WRITE_EXTERNAL_STORAGE,
						Permission.READ_EXTERNAL_STORAGE,
						Permission.ACCESS_COARSE_LOCATION,
						Permission.ACCESS_FINE_LOCATION,
						Permission.CAMERA )
				.onGranted( new Action() {
					@Override
					public void onAction(List<String> permissions) {
						// TODO what to do.
						File externalStorageDirectory = Environment.getExternalStorageDirectory();
						File mj = new File( externalStorageDirectory.getAbsolutePath(), "ImageDownloader" );
						startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
//                        getLocation();
//                        getMobilePhoneNumbers();
					}
				} ).onDenied( new Action() {
			@Override
			public void onAction(List<String> permissions) {
						// TODO what to do
				finish();
			}
		} )
				.start();

	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		if (requestCode==REQUESTCODE){
			if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//				download();
			}else {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("提示");
				builder.setMessage("当前应用没有存储权限,不能使用分享功能，请前往设置");
				builder.setNegativeButton("知道了", null);
				builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						startAppSettings();
					}
				});
				builder.setCancelable(false);
				builder.show();
			}
		}
	}
	/**
	 * 启动应用的设置 来手动开启权限
	 */
	private void startAppSettings() {
		Intent intent = new Intent( Settings.ACTION_MANAGE_WRITE_SETTINGS);
		intent.setData( Uri.parse("package:" + getPackageName()));
		startActivity(intent);
	}

}
